package cn.hzw.supermarket.activity;

import static cn.hzw.supermarket.util.HttpUtil.sendHttpRequest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hzw.supermarket.R;
import cn.hzw.supermarket.adapter.RecyclerViewAdapter;
import cn.hzw.supermarket.databinding.ActivitySearchBinding;
import cn.hzw.supermarket.domain.Goods;
import cn.hzw.supermarket.domain.ShoppingCar;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity {
    private ActivitySearchBinding binding;
    private String args;
    public static List<Goods> goodsInfos = new ArrayList<>();
    Context context;

    final OkHttpClient client = new OkHttpClient();
    public static Goods goods = new Goods();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏标题栏以及状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        /**标题是属于View的，所以窗口所有的修饰部分被隐藏后标题依然有效,需要去掉标题**/
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = ActivitySearchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        context = this;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.gosearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                args = binding.args.getText().toString().trim();
                if(!args.isEmpty()){
                    Log.d("TAG", "args="+args);
                    postRequest("/goodsinfo/searchgoods", args);
                }else{
                    Toast.makeText(SearchActivity.this, "请输入要查询的商品！", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void postRequest(String url, String args)  {
        new Thread(() -> {
            Map<String, String> map = new HashMap<>();
            map.put("args", args);
            Log.d("TAG", "Args="+args);
            String response = sendHttpRequest(url, map);
            if(response!=null&&!response.isEmpty()){
                goodsInfos = JSONObject.parseObject(response,new TypeReference<List<Goods>>(){}.getType());//将JSON字符串转换成对象
                runOnUiThread(() -> binding.recyclerview.setAdapter(getAdapter(JSONObject.parseObject(response,new TypeReference<List<Goods>>(){}.getType()))));
                double totalPrice=0.00;

                DecimalFormat df = new DecimalFormat("######0.00");
                String price = df.format(totalPrice);
                Log.d("TAG", "totalPrice="+totalPrice);
                Log.d("TAG", "price="+price);
                Log.d("TAG", goodsInfos.toString());
            }
        }).start();
    }

    private RecyclerViewAdapter<Goods> getAdapter(List<Goods> infos){
        return new RecyclerViewAdapter<Goods>(this, R.layout.goodslist1, infos) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.goodslist1;
            }

            @Override
            public void convert(ViewHolder holder, Goods data, int position) {
                holder.setImage(R.id.goods_pic, data.getGoodspicture());
                holder.setText(R.id.goods_name, data.getGoodsname());

                String priceText = "￥"+data.getGoodsprice()+"/"+data.getGoodsunit();
                holder.setText(R.id.goods_price, priceText);
                holder.setOnClickListener(R.id.goods, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        Bitmap bitmap = setImage((data.getGoodsPicture()));
                        Bundle bundle = new Bundle();
                        Log.d("TAG5", "onClick: "+data.getGoodspicture());
                        bundle.putString("pic", data.getGoodspicture());
                        bundle.putString("name",data.getGoodsname());
                        bundle.putString("price","￥"+data.getGoodsprice()+"/"+data.getGoodsunit());
                        bundle.putString("content",data.getGoodscontent());
                        Intent intent = new Intent(SearchActivity.this,Details1Activity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);

                    }
                });
            }
        };
    }

//    private void postRequest1(String goodsname,String username)  {
//        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//        JSONObject userJSONObj = new JSONObject();
//        try {
//            userJSONObj.put("goodsname",goodsname);
//            userJSONObj.put("username",username);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        //建立请求表单，添加上传服务器的参数
//        RequestBody userMessage = RequestBody.create(JSON,""+userJSONObj);
//        //发起请求
//        Request request = new Request.Builder()
//                .url("http://10.129.131.201:8080/goodsinfo/selectbyname")
//                .post(userMessage)
//                .build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e){
//                System.out.println(e);
//                System.out.println("连接失败");
//            }
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String goodsresult = response.body().string();//接收从后端传递过来的JSON字符串
//                GoodsResultInfo goodsresultInfo = new GoodsResultInfo();
//                goodsresultInfo = com.alibaba.fastjson.JSONObject.parseObject(goodsresult,GoodsResultInfo.class);//将JSON字符串转换成对象
//
//                goods = goodsresultInfo.getGoods();
//                //System.out.println(goodsresult);
//            }
//        });
//    }
}